from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from typing import List, Optional

from app.services import search_service

app = FastAPI()

# --- CORS Middleware ---
# Allows the frontend to communicate with this backend
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # Allows all origins
    allow_credentials=True,
    allow_methods=["*"],  # Allows all methods
    allow_headers=["*"],  # Allows all headers
)

# --- Pydantic Models ---
class Book(BaseModel):
    id: str
    title: str
    author: Optional[str] = None
    summary: Optional[str] = None
    score: Optional[float] = None

class BookDetails(Book):
    # In the future, we could add more details here
    pass

# --- API Endpoints ---
@app.get("/")
def read_root():
    return {"status": "Story-Verse backend is running"}

@app.get("/api/search", response_model=List[Book])
def search_books(query: str, count: int = 10):
    if not query:
        return []
    results = search_service.search(query, k=count)
    if "error" in results:
        raise HTTPException(status_code=503, detail=results["error"])
    return results

@app.get("/api/books/{book_id}", response_model=BookDetails)
def get_book_details(book_id: str):
    if search_service.book_data is None:
        raise HTTPException(status_code=503, detail="Search service not initialized.")
    try:
        book_info = search_service.book_data.loc[book_id].to_dict()
        book_info['id'] = book_id
        return book_info
    except KeyError:
        raise HTTPException(status_code=404, detail="Book not found")

@app.get("/api/recommend/homepage", response_model=List[Book])
def get_homepage_recommendations(count: int = 10):
    if search_service.book_data is None:
        raise HTTPException(status_code=503, detail="Search service not initialized.")
    
    # For now, return a random sample of books
    sample_df = search_service.book_data.sample(n=count)
    return sample_df.reset_index().to_dict(orient='records') 